const Sequelize = require('sequelize')
const Op = Sequelize.Op
const sequelize = require('../db/dbconfig')
const PostCommentModel = require('../db/models/post_comments')
const PostAndComModel = require('../db/models/postAndCom')
const url = require("url");
const fs = require("querystring");
const postCommentModel = PostCommentModel(sequelize)
const postAndComModel = PostAndComModel(sequelize)

// 增
exports.addPostComment = async (req, res) => {
  try {
    const postComment = req.body
    const user = req.auth
    let results = await postCommentModel.create({
      user_id: user.user_id,
      com_content: postComment.com_content,
      com_level: 1,
      raw:true
    })
    let temp = await postAndComModel.create({
      com_id: results.dataValues.com_id,
      post_id: postComment.post_id,
    })
    res.myMsg('添加成功',0)
  } catch (e) {
    res.myMsg(e)
  }
}
// 删
exports.delPostComment = async (req, res) => {
  try {
    let results = await  postCommentModel.update({
      is_delete: 1
    }, {
      where: {
        com_id: req.params.id
      }
    })
    if(results[0] === 0) return res.myMsg('删除失败，评论不存在')
    res.myMsg('文章评论删除成功',0)
  } catch (e) {
    res.myMsg(e)
  }
}
// 改
exports.updatePostComment = async (req, res) => {
  try {
    const postComment = req.body
    let is_exist = await postCommentModel.findOne({
      where: {
      is_delete: 0,
      com_id: postComment.com_id
      }
    })
    if(is_exist === null) return res.msg('修改失败，文章评论不存在')
    let results = await postCommentModel.update({
      com_content: postComment.com_content
    },{
      where: {
        com_id: postComment.com_id
      }
    })
    res.myMsg('文章评论修改成功')
  } catch (e){
    res.myMsg(e)
  }
}
// 查
exports.getPostCommentByPostId = async (req, res) => {
  try {
    postAndComModel.belongsTo(postCommentModel, {
      foreignKey: 'com_id',
      targetKey: 'com_id',
    });
    const {query} = url.parse(req.url, false);
    let temp = parseInt(fs.parse(query).post_id[0])
    let results = await postAndComModel.findAll({
      include: [
        {
          attributes: ['com_id', 'user_id', 'com_content', 'com_level'],
          model: postCommentModel
        },
      ],
      where: {
        is_delete: 0,
        post_id: temp
      },
      raw: true
    })
    res.myMsg(results,0)
  } catch (e) {
    res.myMsg(e)
  }
}